/*******************************************************************************
 * Copyright 2011 Mile Orešković
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.mileoresko.hsm.examples.phone;

import com.mileoresko.hsm.HSMInternalTransitionAdapter;
import com.mileoresko.hsm.HSMState;
import com.mileoresko.hsm.HierarchicalStateMachine;
import com.mileoresko.hsm.exceptions.HSMDefinitionException;

public class Phone extends HierarchicalStateMachine {
    protected static Phone smInstance;

    public static Phone getStateMachine() {
        if (smInstance == null) {
            try {
                smInstance = new Phone("PHONE_SM");
                smInstance.create();
                smInstance.start(null);
            } catch (final HSMDefinitionException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }
        return smInstance;
    }

    protected Phone(final String label) {
        super(label);
    }

    protected void defineTransitions() {
        try {
            addCommonTransition(PhoneState.IDLE, PhoneEvent.CALL_REQUESTED, PhoneState.CONNECTING, null);
            addCommonTransition(PhoneState.CONNECTING, PhoneEvent.CONNECT_FAILED, PhoneState.IDLE, null);
            addCommonTransition(PhoneState.CONNECTING, PhoneEvent.CONNECT_SUCCESS, PhoneState.DIALING, null);
            addCommonTransition(PhoneState.DIALING, PhoneEvent.RINGING_BACK, PhoneState.RINGING_BACK, null);
            addCommonTransition(PhoneState.DIALING, PhoneEvent.DIALING_FAILED, PhoneState.IDLE, null);
            addCommonTransition(PhoneState.RINGING_BACK, PhoneEvent.CALL_ACCEPTED, PhoneState.IN_CALL, null);
            addCommonTransition(PhoneState.IN_CALL, PhoneEvent.CALL_ENDED_BY_ME, PhoneState.IDLE, null);

            addCommonTransition(PhoneState.IN_CALL, PhoneEvent.NO_OP, null, new HSMInternalTransitionAdapter() {
                public void transitionAction(final Object arg) {
                    smLog("Example of internal transition (just a NO_OP in IN_CALL)");
                }
            });

        } catch (final Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    protected HSMState getInitialState() {
        return PhoneState.IDLE;
    }
}
